package czk.concrent.threadpool;

import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author chenzhangkun
 * @ClassName PriorityThreadPool
 * @description: 实现优先级线程池
 * @date 2024年12月27日
 */
public class PriorityThreadPool {

	public static void main(String[] args) {

		ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
				1,
				1,
				1,
				TimeUnit.SECONDS,
				new PriorityBlockingQueue<>(100)
		);
		for (int i = 0; i < 100; i++) {
			int finalI = i;
			threadPoolExecutor.execute(new PriorityTask(i, () -> {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					throw new RuntimeException(e);
				}
				System.out.println("优先级：" + finalI);
			}));
		}


	}


	/**
	 * 自定义任务
	 * 实现 Runnable 实现比较器
	 * 放入队列时会根据比较器来进行排序
	 */
	public static class PriorityTask implements Runnable, Comparable<PriorityTask> {
		private final int priority;
		private final Runnable task;

		public PriorityTask(int priority, Runnable task) {
			this.priority = priority;
			this.task = task;
		}

		@Override
		public void run() {
			task.run();
		}

		@Override
		public int compareTo(PriorityTask other) {
			// 优先级高的任务应该排在前面（数字越小优先级越大）
			return Integer.compare(this.priority, other.priority);
		}
	}
}
